from Tkinter import *
from tkMessageBox import *
from svn_interface import *
from Queue import Queue, Empty

EXIT     = -1
LOGIN    = -2
PASSWORD = -3
COMMIT   = -4
REFRESH_PERIOD_MS = 100

class StatusUI(object):
  def __init__(self, master, title, callback, show_list=True):
    self.messages = Queue()
    self.responses = Queue()
    self.callback = callback
    self.show_list = show_list

    self.frame = frame = Toplevel(master)
    self.frame.title(title)

    if show_list:
      self.vscroll = Scrollbar(frame)
      self.vscroll.pack(side=RIGHT, fill=Y)
      self.file_list = Listbox(frame, width=80)
      self.file_list.pack(fill=BOTH, expand=1)
      self.vscroll.config(command=self.file_list.yview)
    else:
      self.status = Label(frame, text="Loading...", wraplength=300, width=30, height=5)
      self.status.pack(side=TOP, fill=BOTH, expand=1)

    self.frame.after(REFRESH_PERIOD_MS, self.check_finish)

  # Obtains a commit message
  def get_commit_message(self):
    print "Getting commit message..."
    self.messages.put(COMMIT)
    return self.responses.get()

  # Obtains login credentials
  def get_credentials(self):
    print "Getting credentials..."
    self.messages.put(LOGIN)
    return self.responses.get()

  # Obtains login password
  def get_password(self):
    print "Getting password..."
    self.messages.put(PASSWORD)
    return self.responses.get()

  # Reports a message
  def put(self, message):
    print "Putting message onscreen..."
    self.messages.put(message)

  # Reports completion
  def set_completed(self):
    print "Completed..."
    self.messages.put(EXIT)

  # Update it regularly.
  def check_finish(self):
    try:
      while True:
        message = self.messages.get(False)

        if message == EXIT:
          self.frame.destroy()
          self.callback()
          return
        elif message == LOGIN:
          # TODO: provide previous login info
          # TODO: attempt to use previous info as well...
          LogonUI(self.frame, self.responses.put)
        elif message == PASSWORD:
          # TODO: ask only for password
          LogonUI(self.frame, self.responses.put)
        elif message == COMMIT:
          CommitUI(self.frame, self.responses.put)
        elif self.show_list:
          self.file_list.insert(END, message)
        else:
          self.status.config(text=message)
    except Empty:
      pass
    # Scroll to end of list
    if self.show_list:
      self.file_list.yview(END)

    # TODO: support progress bars

    # Update the status again later.
    self.frame.after(REFRESH_PERIOD_MS, self.check_finish)

